package com.java.item.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.item.entity.Category;
import com.java.item.mapper.CategoryDao;
import com.java.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public List<Category> queryCategoryById(Long pid) {
        return this.list(new LambdaQueryWrapper<Category>().eq(Category::getParentId,pid));
    }

    @Override
    @Transactional
    public void saveNode(Category category) {
        if (this.save(category)) {
            //查询父节点,修改父节点isParent状态
            Category parent = this.getById(category.getParentId());
            if (!parent.getIsParent()) {
                parent.setIsParent(true);
                this.save(parent);
            }
        }

    }

    @Override
    @Transactional
    public void deleteNode(Long id) {
        Category category = this.getById(id);
        Long pid = category.getParentId();
        if (this.removeById(id)) {
            Category parent = this.getById(pid);
            //查询父节点是否还有子节点
            List<Category> categories = this.list(new LambdaQueryWrapper<Category>().eq(Category::getParentId, parent.getId()));
            if (CollUtil.isEmpty(categories)) {
                parent.setIsParent(false);
                this.save(parent);
            }
        }
    }

    @Override
    public List<Category> queryCategoryByBid(Long bid) {
        return categoryDao.queryCategoryByBid(bid);
    }

    @Override
    public List<String> queryCategoryNamesByIds(List<Long> ids) {
        List<Category> categories = categoryDao.selectList(new LambdaQueryWrapper<Category>().in(Category::getId, ids));
        if (CollUtil.isNotEmpty(categories)) {
            return categories.stream().map(Category::getName).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}